package leetcode_题库;

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 *
 * @ProjectName leetcode
 * @Author Ding
 * @CreateTime 2022/8/26 10:45 星期五
 */
public class _145_二叉树的后序遍历 {
    public static void main(String[] args) {

        TreeNode n1 = new TreeNode(3);
        TreeNode n2 = new TreeNode(9);
        TreeNode n3 = new TreeNode(4);
        TreeNode n4 = new TreeNode(5);
        TreeNode n5 = new TreeNode(7);

        n1.left = n2;
        n1.right = n3;
        n3.left = n4;
        n3.right = n5;

//        List<Integer> nn = postorderTraversal(n1);
        List<Integer> nn = postorderTraversalNoDeep(n1);
        System.err.println(nn);
    }

    /**
     * 双栈（由于后序遍历是先序遍历的相反，所以再来一个栈，反向存储即可（效率很差），也可以直接reverse，但都是1ms）
     * > 2022/08/26 11:16:54
     * 解答成功:
     * 执行耗时:1 ms,击败了15.37% 的Java用户
     * 内存消耗:39.4 MB,击败了92.99% 的Java用户
     *
     * @param root
     * @return
     */
    private static List<Integer> postorderTraversalNoDeep(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null){
            return result;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()){
            TreeNode node = stack.pop();
            result.add(node.val);
            if (node.left != null){
                stack.push(node.left);
            }
            if (node.right != null){
                stack.push(node.right);
            }
        }
        Collections.reverse(result);
        return result;
    }


    /**
     * 递归法
     * > 2022/08/26 10:51:49
     * 解答成功:
     * 执行耗时:0 ms,击败了100.00% 的Java用户
     * 内存消耗:39.4 MB,击败了84.48% 的Java用户
     *
     * @param root
     * @return
     */
    public static List<Integer> postorderTraversal(TreeNode root) {
        return postorderTraversal(root, new ArrayList<>());
    }

    public static List<Integer> postorderTraversal(TreeNode root, List<Integer> list) {
        if (root == null) {
            return new ArrayList<>();
        }
        if (root.left != null) {
            postorderTraversal(root.left, list);
        }
        if (root.right != null) {
            postorderTraversal(root.right, list);
        }
        list.add(root.val);
        return list;
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
